package cn.jn.lhm.netty.part06;

import cn.hutool.core.util.StrUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/7/19 - 22:03
 **/
@Slf4j
public class EchoClient {
    public static void main(String[] args) {
        val channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel client) throws Exception {
                        client.pipeline().addLast(new StringEncoder());
                        client.pipeline().addLast(new StringDecoder());
                        client.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                String data = (String) msg;
                                log.info("收到服务断返回的消息：{}", data);
                                super.channelRead(ctx, msg);
                            }
                        });
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));


        channelFuture.addListener((ChannelFutureListener) future -> {
            Channel channel = future.channel();
            new Thread(() -> {
                Scanner scanner = new Scanner(System.in);
                while (true) {
                    String text = scanner.nextLine();
                    if (StrUtil.equals(text, "q")) {
                        // 这里的close也是异步处理的
                        channel.close();
                        log.info("关闭Socket链接");
                        break;
                    }
                    channel.writeAndFlush(text);
                }

            }, "write").start();
        });
    }
}
